package com.rinlink.jbcodec.transform;


import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class NumberToBytes implements Transform<byte[]> {

    ByteBuffer numberBuf;

    public NumberToBytes(float number){
        this.numberBuf = ByteBuffer.allocate(Float.BYTES);
        this.numberBuf.putFloat(number);
    }

    public NumberToBytes(double number){
        this.numberBuf = ByteBuffer.allocate(Double.BYTES);
        this.numberBuf.putDouble(number);
    }

    public NumberToBytes(byte number){
        this.numberBuf = ByteBuffer.allocate(Byte.BYTES);
        this.numberBuf.put(number);
    }

    public NumberToBytes(short number){
        this.numberBuf = ByteBuffer.allocate(Short.BYTES);
        this.numberBuf.putShort(number);
    }

    public NumberToBytes(int number){
        this.numberBuf = ByteBuffer.allocate(Integer.BYTES);
        this.numberBuf.putInt(number);
    }

    public NumberToBytes(long number){
        this.numberBuf = ByteBuffer.allocate(Long.BYTES);
        this.numberBuf.putLong(number);
    }
    public NumberToBytes(float number, String byteOrder){
        this.numberBuf = ByteBuffer.allocate(Float.BYTES);
        this.numberBuf.order(order(byteOrder));
        this.numberBuf.putFloat(number);
    }

    public NumberToBytes(double number, String byteOrder){
        this.numberBuf = ByteBuffer.allocate(Double.BYTES);
        this.numberBuf.order(order(byteOrder));
        this.numberBuf.putDouble(number);
    }

    public NumberToBytes(byte number, String byteOrder){
        this.numberBuf = ByteBuffer.allocate(Byte.BYTES);
        this.numberBuf.order(order(byteOrder));
        this.numberBuf.put(number);
    }

    public NumberToBytes(short number, String byteOrder){
        this.numberBuf = ByteBuffer.allocate(Short.BYTES);
        this.numberBuf.order(order(byteOrder));
        this.numberBuf.putShort(number);
    }

    public NumberToBytes(int number, String byteOrder){
        this.numberBuf = ByteBuffer.allocate(Integer.BYTES);
        this.numberBuf.order(order(byteOrder));
        this.numberBuf.putInt(number);
    }

    public NumberToBytes(long number, String byteOrder){
        this.numberBuf = ByteBuffer.allocate(Long.BYTES);
        this.numberBuf.order(order(byteOrder));
        this.numberBuf.putLong(number);
    }


    public static ByteOrder order(String order){
        if (order == null || order.equalsIgnoreCase("big_engine")){
            return ByteOrder.BIG_ENDIAN;
        }else if (order == null || order.equalsIgnoreCase("little_engine")){
            return ByteOrder.LITTLE_ENDIAN;
        }else {
            throw new IllegalArgumentException("无效的字节排序");
        }
    }

    public byte[] transform() {
        return numberBuf.array();
    }

}
